package com.zjl.spring.第09章_数据校验Validation.D_基于方法实现校验;

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import java.math.BigDecimal;

/**
 * ClassName: D_基于方法实现校验
 * Package: com.zjl.spring.第09章_数据校验Validation
 * Description:
 *
 * @Author 张蛟龙
 * @Create 2024/7/21 18:38
 * @Version 1.0
 */
@Configuration//配置类
@ComponentScan(basePackages = {
        "com.zjl.spring.第09章_数据校验Validation.D_基于方法实现校验",
})//组件扫描
public class D_基于方法实现校验 {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(D_基于方法实现校验.class);

        MethodValidator methodValidator = new MethodValidator();

        //获取校验器
        MyValidator2 bean = context.getBean(MyValidator2.class);

        //会直接抛错
        String s = bean.MyValidator2Test(methodValidator);//执行校验
//        String s = bean.MyValidator2Test(methodValidator);//执行校验

        System.out.println(s);
    }

    @Bean //自动注入  基于方法实现校验类
    public MethodValidationPostProcessor getMethodValidationAdapter(){
        return new MethodValidationPostProcessor();
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class MethodValidator {

    //message  自定义出错信息
    @NotEmpty//限制字符串不为空，并且长度不为0
    @Size(min = 0,max = 200,message="字符过长")//限制字符长度必须在min到max之间
    private String name;

    @NotNull//限制必须不为null
    @Max(value = 200,message= "值太大了")//不大于指定值的数字
    @Min(0)//不小于指定值的数字
    private Integer age;

    @NotNull//限制必须不为null
    @DecimalMax(value = "20000.00")//不大于指定值的数字
    @DecimalMin(value = "0.00")//不小于指定值的数字
    private BigDecimal amt;

    @Pattern(regexp = "(-)?([1-9][0-9]*|0)([.][0-9]+)?",message = "不满足正则")
    @NotBlank()//字符串不为空，并且trim()后不为空串
    private String qian;

}

@Service
@Validated
class MyValidator2{
    public String MyValidator2Test(@Valid @NotNull MethodValidator methodValidator){
        return methodValidator.toString();
    }
}